#include <iostream>
#include <memory>
#include <csignal>
#include "EpollServer.hpp"

// 简单的响应信息处理函数
std::string echoServer(std::string req) {
    std::string uri;
    // Logger::getInstance().loggger()->debug("%s", req.c_str());
    // 解析HTTP请求的URI-----GET /index.html HTTP/1.1
    std::size_t pos = req.find(" ");
    if (pos != std::string::npos) {
        std::size_t pos2 = req.find(" ", pos + 1);
        if (pos2 != std::string::npos) {
            uri = req.substr(pos + 1, pos2 - pos - 1);
        }
    }

    std::string response;
    if (uri == "/") {
        response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<h1>Welcome to the main page!</h1>";
    } else {
        response = "HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\n\r\n<h1>Page not found</h1>";
    }
    return response;
}

// 信号处理函数
void handleInterrupt(int signal) {
    if (signal == SIGINT) {
        Logger::getInstance().loggger()->info("srever done...");
    }
    exit(SERVER_DONE);
}

int main() {
    // 注册信号处理函数
    std::signal(SIGINT, handleInterrupt);
    std::unique_ptr<EpollServer> svr(new EpollServer(echoServer));
    svr->InitServer();
    svr->Start();

    return 0;
}